package com.df.hotfix.loader;

import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class MyJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {
    // 就是一个装饰着模式  ForwardingJavaFileManager

    /**
     * Creates a new instance of ForwardingJavaFileManager.
     *
     * @param fileManager delegate to this file manager
     */
    public MyJavaFileManager(JavaFileManager fileManager) {
        super(fileManager);
    }

    private final Set<OutputFileJavaFileObject> byteArrayJavaFileObjects = new HashSet<>();

    public Set<OutputFileJavaFileObject> getByteArrayJavaFileObjects() {
        return byteArrayJavaFileObjects;
    }

    // 有字节码的输出的时候 我们自定义一个JavaFileObject 来接受输出了
    @Override
    public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
        if (JavaFileObject.Kind.CLASS == kind) {
            OutputFileJavaFileObject byteArrayJavaFileObject = new OutputFileJavaFileObject(className);
            byteArrayJavaFileObjects.add(byteArrayJavaFileObject);
            return byteArrayJavaFileObject;
        } else {
            return super.getJavaFileForOutput(location, className, kind, sibling);
        }
    }
}
